package com.hht.toolanduilibs.util

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.storage.StorageManager
import androidx.annotation.RequiresApi
import com.hht.toolanduilibs.bean.VolumeBean


/**
 * Author:chen'hu
 * Time:2024/5/8 16:01
 * Description:This is StorageManagerUtils
 */
class StorageManagerUtils(mContext: Context) {

    companion object {
        fun newInstance(context: Context): StorageManagerUtils {
            return StorageManagerUtils(context)
        }
    }

    private val mStorageManager: StorageManager =
        mContext.getSystemService(Context.STORAGE_SERVICE) as StorageManager

    @RequiresApi(Build.VERSION_CODES.N)
    @SuppressLint("DiscouragedPrivateApi")
    private fun getUsbDeviceLabel(strMountPath: String): String {
        try {
            val getVolumeList =
                StorageManager::class.java.getDeclaredMethod("getVolumeList", *arrayOfNulls(0))
            getVolumeList.isAccessible = true
            val classStorageVolume = Class.forName("android.os.storage.StorageVolume")
            val getLabel = classStorageVolume.getDeclaredMethod("getUserLabel", *arrayOfNulls(0))
            val storageVolumes = mStorageManager.storageVolumes
            storageVolumes.forEach {
                val path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
                    it.directory?.path else {
                    //26以下的方法还未实例
                }
                if (path == strMountPath) {
                    return getLabel.invoke(it, *arrayOfNulls(0)) as String
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return strMountPath
    }


    @SuppressLint("NewApi")
    fun getUsbList(): List<VolumeBean> {
        val volumeBeanList: MutableList<VolumeBean> = ArrayList()
        try {
            val method = StorageManager::class.java.getDeclaredMethod("getVolumePaths")
            method.isAccessible = true
            val usbList = method.invoke(mStorageManager) as Array<String>
            usbList.forEach {
                if (!it.contains("dev/null") && !it.contains("sdcard") && !it.contains("emulated/0")) {
                    val name = getUsbDeviceLabel(it)
                    val bean = VolumeBean(name, it, 0, 0)
                    volumeBeanList.add(bean)
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return volumeBeanList
    }
}